'use strict'

const { ApiController } = require('jax')
const dayjs = require('dayjs')

class Controller extends ApiController {
  get Model() {
    return this.ctx.model.ActivityConfig
  }

  // 匹配查询
  get searchKey() {
    return ['isOpen']
  }

  // 模糊查询
  get likeKey() {
    return ['title', 'adminMobile']
  }

  // 查询前
  async beforeIndex() {
    const { ctx, config } = this
    const { SYSTEM_TYPE_STORE } = config.constant
    const { query } = ctx
    const { helper } = ctx
    const filter = {}

    if (this.admin.systemType == SYSTEM_TYPE_STORE) throw '非法操作'

    // 关键字模糊查询
    if (query.keyword && !query.keyword == '') {
      const reg = new RegExp(helper.toMongoRegex(query.keyword, 'i'))
      filter.$or = [{ title: reg }]
    }

    // 通过项目名称搜索
    if (query.adminMobile) {
      const adminIds = await ctx.model.Admin.find({
        mobile: new RegExp(helper.toMongoRegex(query.adminMobile), 'i'),
      })
        .limit(10)
        .then((admin) => admin.map((item) => item.id))

      if (adminIds) filter.adminId = { $in: adminIds }
    }

    // 开始时间
    if (query.startDate && query.startDate != '') filter.createdAt = { $gte: query.startDate + ' 00:00:00' }

    // 结束时间
    if (query.endDate && query.endDate != '')
      filter.createdAt = { ...filter.createdAt, $lte: query.endDate + ' 23:59:59' }

    return {
      filter,
    }
  }

  // 格式化
  async formatData(data) {
    const { ctx } = this

    await ctx.model.Admin.findOne({ _id: data.adminId })
      .cache(60)
      .then((res) => {
        data.adminMobile = res.mobile
        data.adminUsername = res.username
      })

    if (data.scope == 1) data.storeCount = await ctx.model.Store.count({ _id: { $in: data.storeIds } })

    if (this.isShow && data.sope) {
      data.stores = await ctx.model.Store.find({
        _id: {
          $in: data.storeIds,
        },
      }).cache(60)
    }

    return data
  }

  // 新增前
  async beforeCreate() {
    const { ctx } = this
    const { SYSTEM_TYPE_STORE } = this.config.constant
    const { body } = ctx.request

    body.adminId = ctx.state.admin.id

    // if (this.admin.systemType == SYSTEM_TYPE_STORE) {
    //   body.storeId = this.admin.sourceId
    //   body.scope = 1
    //   body.storeIds = [this.admin.sourceId]
    // }
  }

  // 新增后
  // async afterCreate(doc) {
  //   this.syncStore(doc)
  // }

  // 发布活动
  async publish() {
    const { ctx } = this
    const { helper } = ctx
    const { body } = ctx.request

    const keys = ['configId']
    const newData = helper.validate(body, {
      required: keys,
      include: keys,
    })

    const activityConfig = await ctx.model.ActivityConfig.findOne({
      _id: newData.configId,
    })

    if (!activityConfig) throw '无效活动'
    if (activityConfig.status != 0) throw '活动状态不正确'
    if (activityConfig.activityDate < dayjs().format('YYYY-MM-DD')) throw '活动时间已过期'

    activityConfig.status = 1
    await activityConfig.save()

    this.syncStore(activityConfig)

    ctx.body = {
      code: 0,
      msg: 'success',
    }
  }

  // 同步数据给门店
  async syncStore(doc) {
    const { ctx } = this
    const { helper } = ctx

    let storeIds = []

    // 全部门店
    if (doc.scope == 0) {
      const stores = await ctx.model.Store.find({
        isOpen: true,
      })

      storeIds = stores.map((item) => item.id)
    } else {
      storeIds = doc.storeIds
    }

    for (let i = 0; i < storeIds.length; i++) {
      const storeId = storeIds[i]
      const activitys = []
      doc.activityTimes.map((item) => {
        const newData = {
          storeId,
          title: doc.title,
          activityDate: doc.activityDate,
          startTime: `${doc.activityDate} ${item.start}`,
          endTime: `${doc.activityDate} ${item.end}`,
          adminId: this.admin.id,
          isOpen: true,
        }
        activitys.push(newData)
      })

      await helper.queue(activitys, async (activity) => {
        const { storeId, startTime, endTime } = activity

        const doc = await ctx.model.Activity.findOne({
          storeId,
          $or: [
            // 情况1：活动的开始时间在某个已有会议的时间段内
            { startTime: { $lt: startTime }, endTime: { $gt: startTime } },
            // 情况2：活动的结束时间在某个已有会议的时间段内
            { startTime: { $lt: endTime }, endTime: { $gt: endTime } },
            // 情况3：活动完全包含某个已有会议
            { startTime: { $gte: startTime }, endTime: { $lte: endTime } },
          ],
        })

        if (!doc) {
          await ctx.model.Activity.create(activity)
        } else {
          console.error('发布失败，时间冲突')
        }
      })
    }
  }

  // 保存前
  async beforeSave() {
    const { ctx } = this
    const { body } = ctx.request

    if (body.activityTimes) {
      body.activityTimes = body.activityTimes.map((item) => {
        return {
          start: `${body.activityDate} ${item.start}`,
          end: `${body.activityDate} ${item.end}`,
        }
      })
    }
  }
}

module.exports = Controller
